<template>
  <div class="main">
    <div class="login-container">
      <el-card class="login-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <h3 class="login-title">
              <el-icon class="title-icon"><User /></el-icon>
              用户登录
            </h3>
          </div>
        </template>

        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          label-width="80px"
          size="large"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              prefix-icon="User"
              clearable
            />
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
              clearable
              @keyup.enter="handleLogin"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="handleLogin"
              class="login-btn"
              :loading="loading"
              size="large"
            >
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>

          <div class="register-link">
            <el-link @click="goToRegister" type="primary">
              没有账号？立即注册
            </el-link>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { loginApi } from '@/utils/api'
import { setUserInfo, getRoleDisplayName } from '@/utils/auth'

const router = useRouter()
const loginFormRef = ref()
const loading = ref(false)

// 表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    const valid = await loginFormRef.value.validate()
    if (!valid) return

    loading.value = true
    const res = await loginApi({
      username: loginForm.username,
      password: loginForm.password
    })

    if (res.code === 200) {
      const {
        user_id,
        username,
        full_name,
        phone_number,
        email,
        role,
        token,
      } = res.data[0]

      // 构建用户信息对象
      const userInfo = {
        user_id,
        username,
        full_name,
        phone_number,
        email,
        role: role || 'user', // 默认为普通用户
        token,
      }

      // 使用权限工具类存储用户信息
      setUserInfo(userInfo)

      // 显示登录成功消息，包含角色信息
      const roleDisplay = getRoleDisplayName(userInfo.role)
      ElMessage.success({
        message: `登录成功！欢迎您，${roleDisplay}`,
        duration: 2000,
      })

      // 根据用户角色跳转到不同页面
      const redirectPath = userInfo.role === 'admin' ? '/home/alluser' : '/home/rest'
      router.push({ path: redirectPath })
    } else {
      ElMessage.error({
        message: res.message || '登录失败',
        duration: 1500,
      })
    }
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error({
      message: '网络错误，请稍后重试',
      duration: 1500,
    })
  } finally {
    loading.value = false
  }
}

// 跳转到注册页面
const goToRegister = () => {
  router.push({ path: '/register' })
}
</script>

<style lang="less" scoped>
.main {
  background-image: url("@/assets/bglogin.jpg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
    z-index: 1;
  }
}

.login-container {
  position: relative;
  z-index: 2;
  width: 100%;
  max-width: 450px;
  margin: 0 20px;
}

.login-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;

  :deep(.el-card__header) {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-bottom: none;
    padding: 20px;
  }

  :deep(.el-card__body) {
    padding: 30px;
  }
}

.card-header {
  text-align: center;
}

.login-title {
  color: white;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;

  .title-icon {
    font-size: 28px;
  }
}

.login-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  }

  &:active {
    transform: translateY(0);
  }
}

.register-link {
  text-align: center;
  margin-top: 20px;

  .el-link {
    font-size: 14px;
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .main {
    padding: 20px;
  }

  .login-container {
    max-width: 100%;
    margin: 0;
  }

  .login-card {
    :deep(.el-card__body) {
      padding: 20px;
    }
  }

  .login-title {
    font-size: 20px;
  }
}

// 表单样式优化
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  &.is-focus {
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  }
}
</style>
